import redis
import datetime
import pymysql
# V2为：无需执行一次 V1为：需要执行一次
# LOG_DIVICE_ACTIVE_V2_ZJKJ_20221030 为20221030日早间服务当前总订阅量  LOG_DIVICE_NEW_ACTIVE_V2_ZJKJ 为20221030日早间服务当天纯新增订阅量
# LOG_DIVICE_ACTIVE_V2_ONCE7_ZJKJ 截止7日前曾经订阅过早间服务的设备激活id LOG_DIVICE_ACTIVE_V2_RETENTION7_ZJKJ  从新增后7天仍然订阅的设备
# LOG_DIVICE_ACTIVE_V2_ONCE_ALL 曾经订阅过生活助手的设备激活id
# redis
def getReidsConnection():
    redis_info = {
        "host": "172.20.151.90",
        "password": "Coocaa2022",
        "port": 6379,
        "db": 8
    }

    r = redis.Redis(**redis_info, decode_responses=True)
    return r

def main1():
	#LOG_DIVICE_ACTIVE_V2_* 为服务当前总订阅量  LOG_DIVICE_NEW_ACTIVE_V2_* 为服务当天订阅量
    key1 = "LOG_DIVICE_ACTIVE_V2"
    key2 = "LOG_DIVICE_NEW_ACTIVE_V2"
    serId = "_ZJKJ"
    date = "_20220630"
    selectKey(key2+serId+date)
    selectKey(key1+serId+date)

def addKey(key,aId):
    r = getReidsConnection()
    r.sadd(key,aId)

def addStringKey(key, value):
        r = getReidsConnection()
        r.set(key, value)

def deleteKey(key):
    r = getReidsConnection()
    r.delete(key)

def selectKey(key):
    r = getReidsConnection()
    num = r.scard(key)
    print(f"{key}的长度为{num}")
    return num

def getValueByKey(key):
    r = getReidsConnection()
    value = r.get(key)
    print(f"{key}的值为{value}")

#获取截止7天前曾经订阅过的设备
#serId 为服务 day 天数
def selectAllKey(serId,day):
    r = getReidsConnection()
    keys = r.keys()
    #print (type(keys))
    newKey = f'LOG_DIVICE_ACTIVE_V2_ONCE{day}_{serId}'
    date7 = getdate(day)
    print(date7)
    for key in keys:
        if key.__contains__(f'LOG_DIVICE_NEW_ACTIVE_V2_{serId}'):
            day = key[-8:]
            if(int(day)<=int(date7)):
                r.sunionstore(newKey,key,newKey)
                print(f"{key}数量为:{r.scard(key)}")
                #print(r.sunion(key,newKey))
                print(f"取交集后:{newKey}数量为:{r.scard(newKey)}")

#获取 从新增 后7天 仍然订阅的设备
#serId 服务 day 天数
def selectAllKey_Retention(serId,day):
    r = getReidsConnection()
    keys = r.keys()
    #print (type(keys))
    newKey = f'LOG_DIVICE_ACTIVE_V2_RETENTION{day}_{serId}'
    newTempKey = f'LOG_DIVICE_ACTIVE_V2_TEMP{day}_{serId}'
    for key in keys:
        if key.__contains__(f'LOG_DIVICE_NEW_ACTIVE_V2_{serId}'):
            print(f"原来的：{key},数量为:{r.scard(key)}")
            date7 = strToTime(key[-8:],day)
            date7key = f"LOG_DIVICE_ACTIVE_V2_{serId}_{date7}"
            print(f"转换后：{date7key},数量为:{r.scard(date7key)}")
            # N日且N+7日服务处于打开的设备
            r.sinterstore(newTempKey,key,date7key)
            r.sunionstore(newKey, newTempKey, newKey)
            print(f"取交集后:{newKey}数量为:{r.scard(newKey)}")

#获取截止目前为止累计订阅数
#serId 为服务 executeFlag执行标志 0:不需要执行 1:需要执行
def selectAllOnceKey(serId,executeFlag):
    if executeFlag == 1:
        # redis key
        redisStr = 'V1'
    else:
        redisStr = 'V2'
    r = getReidsConnection()
    keys = r.keys()
    #print (type(keys))
    newKey = f'LOG_DIVICE_ACTIVE_{redisStr}_ONCE_{serId}'
    for key in keys:
        if key.__contains__(f'LOG_DIVICE_ACTIVE_{redisStr}_{serId}'):
            r.sunionstore(newKey,key,newKey)
            print(f"{key}数量为:{r.scard(key)}")
            #print(r.sunion(key,newKey))
            print(f"取交集后:{newKey}数量为:{r.scard(newKey)}")

#修改redis key值
def renameKey(serId):
    r = getReidsConnection()
    keys = r.keys()
    # print (type(keys))
    for key in keys:
        if key.__contains__(f'LOG_DIVICE_ACTIVE_V1_ONCE_{serId}'):
            #newKey = f'LOG_DIVICE_NEW_ACTIVE_V1_{serId}_{key[-8:]}'
            newKey = f'LOG_DIVICE_ACTIVE_V1_ONCE7_{serId}'
            print(f'旧key:{key}')
            print(f'新key:{newKey}')
            r.rename(key,newKey)
        if key.__contains__(f'LOG_DIVICE_ACTIVE_V1_RETENTION_{serId}'):
            #newKey = f'LOG_DIVICE_NEW_ACTIVE_V1_{serId}_{key[-8:]}'
            newKey = f'LOG_DIVICE_ACTIVE_V1_RETENTION7_{serId}'
            print(f'旧key:{key}')
            print(f'新key:{newKey}')
            r.rename(key,newKey)

def printKeys(serId):
    r = getReidsConnection()
    keys = r.keys()
    # print (type(keys))
    for key in keys:
        if key.__contains__(f'LOG_DIVICE_ACTIVE_V2_ONCE_{serId}'):
            print(f'key:{key}')

#获取流失订阅设备
def test01():
    r = getReidsConnection()
    redisStr = 'V2'
    serId = 'zjkj'
    todoKey = f"LOG_DIVICE_ACTIVE_{redisStr}_{serId.upper()}_{toDay}"
    beforeKey = f"LOG_DIVICE_ACTIVE_{redisStr}_{serId.upper()}_{beforeDay}"
    newKey = f"LOG_DIVICE_NEW_ACTIVE_{redisStr}_{serId.upper()}_{toDay}"
    # 取 在当日订阅设备 但不在昨日的订阅设备中的 设备 作为当日的新增设备 存入redis
    r.sdiffstore(newKey, beforeKey, todoKey)
    todoNun = r.scard(todoKey)
    beforeNun = r.scard(beforeKey)
    newNun = r.scard(newKey)
    logDetail = f'{todoKey}日累计订阅设备{todoNun},昨日累计订阅设备{beforeNun},今日流失订阅设备{newNun}'
    print(logDetail)

def setZjkjOpenTime():
    r = getReidsConnection()


#将指定字符串 dateStr ,偏移 offsetInt 天后再输出字符串
#如 20220805 偏移7天 即增加7天后 输出 20220812
def strToTime(dateStr,offsetInt):
    t = datetime.datetime.strptime(dateStr, "%Y%m%d")
    #print(t)
    offset = datetime.timedelta(days=offsetInt)
    re_date = (t+offset).strftime('%Y%m%d')
    #print(re_date)
    return  re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y%m%d')
    return re_date



if __name__ == '__main__':
    toDay = getdate(1)
    beforeDay = getdate(2)
    #selectAllOnceKey("ZJKJ",0)
    #test01()
    #LOG_DIVICE_ACTIVE_V2_* 为服务当前总订阅量  LOG_DIVICE_NEW_ACTIVE_V2_* 为服务当天订阅量
    #selectKey(key1+serId+date)
    #renameKey('ALL')
    #selectAllKey('ALL',7)
    #selectAllKey_Retention('ALL',7)
    addStringKey("SJTX_VERSION","2302020000")
    addStringKey("ZJKJ_VERSION","2302030000")
    addStringKey("ZJTX_VERSION","2302040000")
    addStringKey("YJYL_VERSION","2302050000")
    addStringKey("JKZX_VERSION","2302060000")
    getValueByKey("JKZX_VERSION")
    #selectKey("CORPUS_CONTENT_ALERT_51")
    #deleteKey("LOG_DIVICE_ACTIVE_V2_ONCE_ZJKJ")
    #printKeys("")
    #selectAllKey_Retention("ALL")
    #selectAllKey_Retention("JKZX")
    #selectAllKey_Retention("YJYL")
    #selectAllKey_Retention("ZJTX")
    #getValueByKey("CORPUS_CONTENT_ALERT_51")

